import Axios from 'axios'
import qs from 'qs'
import iView from 'iview'
import { NO_LOGIN,FAIL,ERR_OK } from 'api/config'
import router from '@/router/index'
import Config from '@/config'


const axiosCreate = Axios.create({
    //设置主要域名
    baseURL: Config.recuitUrl,
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
    },
})

// 解析参数
let deCodeParams = (str) => {
    let scene = str.split('&');
    let ajaxData = {}
    for (var i = 0, l = scene.length; i < l; i++) {
        var keyValueArr = scene[i].split('='),
            key = keyValueArr[0],
            value = keyValueArr[1];

        if (key && value) ajaxData[key] = value;
    }
    return ajaxData
}

// 拦截器
axiosCreate.interceptors.request.use((config) => {
    iView.LoadingBar.start()
    console.log(config,"config")
    // 设置头部
    config.withCredentials = true;
    if (config.method === 'post') config.data = qs.stringify(config.data);
    // 传debug 走测试接口
    // if(config.data && deCodeParams(config.data).debug){
    //     config.baseURL = Config.developUrl
    // }

    return config;
});

// 添加响应拦截器
axiosCreate.interceptors.response.use((response) => {
    iView.LoadingBar.finish()
    if(response.data.status == ERR_OK){
        iView.LoadingBar.finish()
    }
    let {data} = response;
    if(data){
        switch(data.status){
            case 'error':// 业务逻辑错误
            {
                // iView.Message.warning(data.message)
                return Promise.reject(data.message)
            }
            case 'success':// 成功
            {
                return Promise.resolve(data.data)
            }
            break;
            case 'no-login':// 未登录
            {
                router.replace("/login");
                return Promise.reject()
            }
            case 'empower-not-done':// 接入未完成
            {
                // this.$router.replace("/consumerAccess");
                router.push({name:'consumerAccess',params:{step:data.step}})
                return Promise.reject()
            }
        }
    }
    return response.data.data;
}, (error) => {
    iView.LoadingBar.error()
    return Promise.reject(error)
});

export default axiosCreate